package com.acwer.drgs.performance.config;

import com.acwer.common.RpnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：gongbo
 * @Date：2021/12/2017:23
 */
public class HttpUtils {

    private StringHttpMessageConverter m = new StringHttpMessageConverter(Charset.forName("UTF-8"));

    RestTemplate restTemplate = new RestTemplate();


    public HttpEntity<MultiValueMap<String, String>> generatePostJson(MultiValueMap<String, String> jsonMap) {

        //如果需要其它的请求头信息、都可以在这里追加
        HttpHeaders httpHeaders = new HttpHeaders();

        MediaType type = MediaType.APPLICATION_FORM_URLENCODED;

        httpHeaders.setContentType(type);

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(jsonMap, httpHeaders);


        return httpEntity;
    }

    /**
     * post请求、请求参数为json
     *
     * @return
     */
    public RpnMsg sendPost(String json, String url) {
        //String uri = "http://127.0.0.1:80";
       // restTemplate.setMessageConverters(m);
        MultiValueMap<String, String> jsonMap = new LinkedMultiValueMap<>(6);
        jsonMap.add("json", json);
        HttpEntity<MultiValueMap<String, String>> map = generatePostJson(jsonMap);
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<RpnMsg> apiResponse = restTemplate.exchange
                (
                        url, method,
                        generatePostJson(jsonMap),
                        RpnMsg.class
                );
        return apiResponse.getBody();
    }
}



